import 'dart:async';
import 'dart:io';

import 'package:aliplayer_widget/utils/log_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_android/billing_client_wrappers.dart';
import 'package:in_app_purchase_android/in_app_purchase_android.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';
import 'package:yyshort/common/apis/goods_api.dart';
import 'package:yyshort/common/model/goods_model.dart';
import 'package:yyshort/common/model/video_model.dart';
import 'package:yyshort/common/widgets/toast.dart';
import 'package:yyshort/pages/payment/widgets/consumable_store.dart';
import 'package:yyshort/pages/personal/personal/controller.dart';

import 'state.dart';

// 内购相关常量定义
// iOS平台必须自动消耗消耗品，其他平台可配置
final bool _kAutoConsume = Platform.isIOS || false;

// 商品ID定义
const String _kConsumableId = 'standard_coin_199'; // 消耗品ID
const String _kUpgradeId = 'upgrade'; // 非消耗品（升级）ID
const String _kSilverSubscriptionId = 'subscription_silver'; // 白银订阅ID
const String _kGoldSubscriptionId = 'subscription_gold'; // 黄金订阅ID

// 所有商品ID列表，用于从应用商店查询商品信息
List<String> _kProductIds = <String>[
  'test_1.99'
  // 'standard_coin_199',
  // 'standard_coin_1299',
  // 'standard_coin_1499',
  // 'standard_coin_1699',
  // 'standard_coin_2099',
  // 'standard_coin_2299',
  // 'standard_coin_2499',
  // _kConsumableId,
  // _kUpgradeId,
  // _kSilverSubscriptionId,
  // _kGoldSubscriptionId,
];

/// 内购功能核心控制器
/// 职责：处理内购相关的所有业务逻辑，包括商品加载、发起购买、处理购买结果等
class PaymentController extends GetxController {
  // 状态管理实例，存储所有响应式变量
  final PaymentState state = PaymentState();

  // 内购插件实例
  final InAppPurchase _inAppPurchase = InAppPurchase.instance;

  // 购买状态监听订阅流
  late StreamSubscription<List<PurchaseDetails>> _subscription;

  // 添加一个标记，用于控制是否处理恢复订单
  bool _shouldProcessRestoredPurchases = false; // 初始化为false，不处理初始化时的恢复订单

  @override
  Future<void> onInit() async {
    // 初始化购买状态监听器
    _initPurchaseListener();

    await fetchRechargeList();
    super.onInit();

    // 初始化商店信息（查询商品列表等）
    initStoreInfo();
  }

  /// 处理购买逻辑
  Future<void> clickGoods(GoodsModel goods) async {
    if (state.isNeedLoading.value == true) {
      return;
    }
    EasyLoading.show();
    state.isNeedLoading.value = true;
    print('Purchasing ${goods.name} for \$${goods.goodUsPrice}');
    // 区分平台选择支付类型
    String payType = GetPlatform.isIOS ? '2' : '1';
    state.order_id.value = await createOrder(goods.id.toString(), payType);

    print('---创建订单ID--${state.order_id.value}');

    if (state.order_id.value != '') {
      //根据服务端商品ID，查询平台对应商品信息，开始购买；
      ProductDetails matchedProduct = state.products.firstWhere((product) {
        return product.id == goods.goodId;
      });
      buyProduct(matchedProduct);
    }
  }

  /// 创建订单
  /// gearId = 价格档位ID
  Future<String> createOrder(String gearId, String payType) async {
    try {
      String result = '';
      if (state.episodeModel != null) {
        //视频内充值
        result = await GoodsAPI.create_order(
          gearId,
          payType,
          episodeModel: state.episodeModel!,
        );
      } else {
        result = await GoodsAPI.create_order(gearId, payType);
      }
      print('订单创建结果: $result');
      return result;
      // 可以在这里处理订单创建后的逻辑，如发起支付等
    } catch (e) {
      print('创建订单失败: $e');
      return '';
    }
  }

  @override
  void onClose() {
    // 清理工作：取消订阅，避免内存泄漏
    _subscription.cancel();

    // iOS平台特定清理：移除支付队列代理
    if (Platform.isIOS) {
      final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition =
          _inAppPurchase
              .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      iosPlatformAddition.setDelegate(null);
    }

    super.onClose();
    EasyLoading.dismiss();
  }

  /// 获取充值档位列表
  Future<void> fetchRechargeList() async {
    try {
      var result = await GoodsAPI.get_recharge_list();
      if (result != null && result is List) {
        // 区分消耗类型和订阅类型商品
        state.conTypeList.value = result
            .where((item) => item is GoodsModel && item.goodType == 1)
            .cast<GoodsModel>()
            .toList();

        state.subTypeList.value = result
            .where((item) => item is GoodsModel && item.goodType != 1)
            .cast<GoodsModel>()
            .toList();
      }

      // 收集所有商品的goodId并去重
      final List<String> allGoodIds = [
        ...state.conTypeList.value.map((goods) => goods.goodId!),
        ...state.subTypeList.value.map((goods) => goods.goodId!),
      ];
      _kProductIds = List.from(allGoodIds);
    } catch (e) {
      print('获取充值列表失败: $e');
    }
  }

  Future<void> _handlePurchases(List<PurchaseDetails> purchases) async {
    for (var purchase in purchases) {
      if (purchase.status == PurchaseStatus.purchased ||
          purchase.status == PurchaseStatus.restored) {
        // 处理历史订单（验证、发放商品等）
        await _inAppPurchase.completePurchase(purchase);
      }
    }
  }

  /// 初始化购买状态监听器
  /// 作用：实时监听购买状态变化（如购买中、购买成功、购买失败等）
  void _initPurchaseListener() {
    // 获取购买状态更新流
    final Stream<List<PurchaseDetails>> purchaseUpdated =
        _inAppPurchase.purchaseStream;

    // 订阅购买状态更新
    _subscription = purchaseUpdated.listen(
      (List<PurchaseDetails> purchaseDetailsList) {
        // _handlePurchases(purchaseDetailsList);

        // 处理购买状态更新
        _listenToPurchaseUpdated(purchaseDetailsList);
      },
      onDone: () {
        // 流结束时取消订阅
        _subscription.cancel();
        state.isNeedLoading.value = false;
      },
      onError: (Object error) {
        // 处理监听错误
        _handlePurchaseError(error);
        state.isNeedLoading.value = false;
      },
    );
  }

  /// 初始化商店信息
  /// 步骤：1. 检查内购服务是否可用 2. 配置平台特定设置 3. 查询商品详情 4. 加载已购买的消耗品
  Future<void> initStoreInfo() async {
    // 标记为加载中状态
    state.loading.value = true;

    // 检查内购服务是否可用
    final bool isAvailable = await _inAppPurchase.isAvailable();
    state.isAvailable.value = isAvailable;

    // 如果内购服务不可用，更新状态并返回
    if (!isAvailable) {
      _updateState(
        purchases: [],
        products: [],
        notFoundIds: [],
        consumables: [],
        loading: false,
      );
      return;
    }

    // iOS平台特定配置：设置支付队列代理
    if (Platform.isIOS) {
      final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition =
          _inAppPurchase
              .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      await iosPlatformAddition.setDelegate(ExamplePaymentQueueDelegate());
    }

    // 从应用商店查询商品详情
    // final ProductDetailsResponse productDetailResponse =
    //     await _inAppPurchase.queryProductDetails(_kProductIds.toSet());
    final ProductDetailsResponse productDetailResponse = await _inAppPurchase
        .queryProductDetails(_kProductIds.toSet());

    // 处理商品查询错误
    if (productDetailResponse.error != null) {
      _updateState(
        queryProductError: productDetailResponse.error!.message,
        products: productDetailResponse.productDetails,
        notFoundIds: productDetailResponse.notFoundIDs,
        loading: false,
      );
      return;
    }

    // 处理无商品的情况
    if (productDetailResponse.productDetails.isEmpty) {
      _updateState(
        products: productDetailResponse.productDetails,
        notFoundIds: productDetailResponse.notFoundIDs,
        loading: false,
      );
      return;
    }

    // 加载已购买的消耗品列表
    final List<String> consumables = await ConsumableStore.load();

    // 更新状态
    _updateState(
      products: productDetailResponse.productDetails,
      notFoundIds: productDetailResponse.notFoundIDs,
      consumables: consumables,
      loading: false,
    );
  }

  /// 更新状态的统一方法
  /// 作用：集中处理状态更新，确保状态变更的一致性
  void _updateState({
    List<ProductDetails> products = const [],
    List<String> notFoundIds = const [],
    List<PurchaseDetails> purchases = const [],
    List<String> consumables = const [],
    bool purchasePending = false,
    bool loading = true,
    String queryProductError = '',
  }) {
    state.products.value = products;
    state.notFoundIds.value = notFoundIds;
    state.purchases.value = purchases;
    state.consumables.value = consumables;
    state.purchasePending.value = purchasePending;
    state.loading.value = loading;
    state.queryProductError.value = queryProductError;
  }

  /// 恢复购买
  /// 作用：恢复用户过往的购买记录（主要用于非消耗品和订阅）
  Future<void> restorePurchases() async {
    if (state.isAvailable.value) {
      try {
        // 手动触发恢复前，设置标记为true，允许处理恢复的订单
        _shouldProcessRestoredPurchases = true;
        await _inAppPurchase.restorePurchases();
        toastInfo(msg: "${'正在恢复购买'.tr}...");
      } catch (e) {
        toastInfo(msg: "${'恢复购买失败'.tr}: ${e.toString()}");
        _shouldProcessRestoredPurchases = false; // 出错时重置标记
      }
    } else {
      toastInfo(msg: "内购服务不可用，无法恢复购买".tr);
    }
  }

  /// 消耗消耗品
  /// [id]：消耗品的购买ID
  Future<void> consume(String id) async {
    await ConsumableStore.consume(id);
    final List<String> consumables = await ConsumableStore.load();
    state.consumables.value = consumables;
  }

  /// 发起购买
  /// [productDetails]：要购买的商品详情
  Future<void> buyProduct(ProductDetails productDetails) async {
    late PurchaseParam purchaseParam;
    print('--------后台订单号：${state.order_id.value}');
    // 根据平台创建不同的购买参数
    if (Platform.isAndroid) {
      // 对于Android平台，处理订阅升级/降级逻辑
      final GooglePlayPurchaseDetails? oldSubscription = _getOldSubscription(
        productDetails,
      );

      purchaseParam = GooglePlayPurchaseParam(
        productDetails: productDetails,
        changeSubscriptionParam: (oldSubscription != null)
            ? ChangeSubscriptionParam(
                oldPurchaseDetails: oldSubscription,
                replacementMode: ReplacementMode.withTimeProration,
              )
            : null,
      );
    } else {
      // iOS平台直接创建购买参数
      purchaseParam = PurchaseParam(
        productDetails: productDetails,
        applicationUserName: state.order_id.value,
      );
    }

    // 根据商品类型发起不同的购买请求
    // 检查subTypeList中是否存在id与productDetails.id相等的元素
    // ignore: invalid_use_of_protected_member
    bool hasMatchingId = state.subTypeList.value.any((goodsModel) {
      // 假设GoodsModel中有一个与productDetails.id对应的id字段，比如叫productId
      return goodsModel.goodId == productDetails.id;
    });

    // 购买消耗品
    try {
      if (!hasMatchingId) {
        await _inAppPurchase.buyConsumable(
          purchaseParam: purchaseParam,
          autoConsume: _kAutoConsume,
        );
      } else {
        // 购买非消耗品或订阅
        await _inAppPurchase.buyNonConsumable(purchaseParam: purchaseParam);
      }
    } on PlatformException catch (e) {
      print('购买过程中发生错误: ${e.code}');
      print('购买过程中发生错误: ${e.message}');
      print('购买过程中发生错误: ${e.details}');
      EasyLoading.dismiss();
      if (e.code == 'storekit2_purchase_cancelled') {
      } else {}
      state.isNeedLoading.value = false;
    }
  }

  /// 处理购买状态更新
  /// [purchaseDetailsList]：购买详情列表
  Future<void> _listenToPurchaseUpdated(
    List<PurchaseDetails> purchaseDetailsList,
  ) async {
    for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
      // 对于恢复的订单，只有标记为true时才处理
      if (purchaseDetails.status == PurchaseStatus.restored &&
          !_shouldProcessRestoredPurchases &&
          state.order_id.value == '') {
        // 忽略初始化时的恢复订单，不做处理
        await _inAppPurchase.completePurchase(purchaseDetails);
        continue;
      }
      // 处理购买中状态
      if (purchaseDetails.status == PurchaseStatus.pending) {
        _updateState(purchasePending: true);
      } else {
        // 处理购买错误状态
        if (purchaseDetails.status == PurchaseStatus.error) {
          EasyLoading.showInfo(purchaseDetails.error!.message);
          state.isNeedLoading.value = false;
          _handleError(purchaseDetails.error!);
        } else if (purchaseDetails.status == PurchaseStatus.canceled) {
          EasyLoading.dismiss();
          state.isNeedLoading.value = false;
        }
        // 处理购买成功或恢复购买状态
        else if (purchaseDetails.status == PurchaseStatus.purchased ||
            purchaseDetails.status == PurchaseStatus.restored) {
          logd('-------订单ID-商品状态---${purchaseDetails.status}');
          logd(
            '-------订单ID-商品productID状态---${purchaseDetails.productID.toString()}',
          );
          logd(
            '-------订单ID-商品purchaseID状态---${purchaseDetails.purchaseID.toString()}',
          );

          // 验证购买的有效性（实际应用中应通过服务器验证）
          final bool valid = await _verifyPurchase(purchaseDetails);
          state.order_id.value = '';
          if (valid) {
            // await _inAppPurchase.completePurchase(purchaseDetails);
            // 验证通过，交付商品，
            // await _deliverProduct(purchaseDetails);
            Get.lazyPut(() => PersonalController());
            //更新用户信息
            final PersonalController temPonnalCTL =
                Get.find<PersonalController>();
            temPonnalCTL.onReady();
            EasyLoading.showSuccess('');
            state.isNeedLoading.value = false;
          } else {
            _handleInvalidPurchase(purchaseDetails);
            await _inAppPurchase.completePurchase(purchaseDetails);
            state.isNeedLoading.value = false;
            EasyLoading.dismiss();
            // EasyLoading.showError('验证接口失败');
            return;
          }
        }

        // Android平台：手动消耗消耗品（如果需要）
        if (Platform.isAndroid) {
          final InAppPurchaseAndroidPlatformAddition androidAddition =
              _inAppPurchase
                  .getPlatformAddition<InAppPurchaseAndroidPlatformAddition>();
          await androidAddition.consumePurchase(purchaseDetails);
        }

        // 完成购买流程（通知应用商店交易已完成）
        // ios 沙盒 purchaseDetails.pendingCompletePurchase 无效；
        // 关键修复：无论状态如何，只要需要就完成购买（沙盒环境强制闭环）
        if (purchaseDetails.pendingCompletePurchase || Platform.isIOS) {
          // iOS 沙盒强制调用，避免状态残留
          await _inAppPurchase.completePurchase(purchaseDetails);
          // 重置 pending 状态
          // _updateState(purchasePending: false);
        } else {
          if (purchaseDetails.pendingCompletePurchase) {
            await _inAppPurchase.completePurchase(purchaseDetails);
          }
        }
      }
    }
  }

  bool isProductInList(String productId, RxList<GoodsModel> conTypeList) {
    // 遍历列表，检查是否有匹配的goodId
    return conTypeList.any((goods) => goods.goodId == productId);
  }

  /// 确认价格变更（仅iOS）
  /// 作用：当订阅价格发生变化时，向用户显示确认对话框
  Future<void> confirmPriceChange() async {
    if (Platform.isIOS) {
      final InAppPurchaseStoreKitPlatformAddition iapStoreKitPlatformAddition =
          _inAppPurchase
              .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      await iapStoreKitPlatformAddition.showPriceConsentIfNeeded();
    }
  }

  /// 获取旧的订阅信息（仅Android）
  /// 作用：处理订阅升级/降级逻辑时需要提供旧的订阅信息
  GooglePlayPurchaseDetails? _getOldSubscription(
    ProductDetails productDetails,
  ) {
    // 构建当前购买的映射表（商品ID -> 购买详情）
    final Map<String, PurchaseDetails> purchases =
        Map<String, PurchaseDetails>.fromEntries(
          state.purchases.map((PurchaseDetails purchase) {
            return MapEntry<String, PurchaseDetails>(
              purchase.productID,
              purchase,
            );
          }),
        );

    GooglePlayPurchaseDetails? oldSubscription;
    // 处理白银订阅升级到黄金订阅的情况
    if (productDetails.id == _kSilverSubscriptionId &&
        purchases[_kGoldSubscriptionId] != null) {
      oldSubscription =
          purchases[_kGoldSubscriptionId]! as GooglePlayPurchaseDetails;
    }
    // 处理黄金订阅降级到白银订阅的情况
    else if (productDetails.id == _kGoldSubscriptionId &&
        purchases[_kSilverSubscriptionId] != null) {
      oldSubscription =
          purchases[_kSilverSubscriptionId]! as GooglePlayPurchaseDetails;
    }
    return oldSubscription;
  }

  /// 验证购买的有效性(苹果订单是否被篡改)
  /// 重要：实际应用中必须通过服务器验证购买凭证，这里仅作示例
  Future<bool> _verifyPurchase(PurchaseDetails purchaseDetails) async {
    if (Platform.isAndroid) {
      bool checkOrderResult = await GoodsAPI.google_pay_verify_order(
        state.order_id.value,
        purchaseDetails.purchaseID.toString(),
        purchaseDetails.productID,
        purchaseDetails.verificationData.serverVerificationData,
      );
      return checkOrderResult;
    } else {
      bool exists = isProductInList(
        purchaseDetails.productID,
        state.conTypeList,
      );
      if (exists) {
        logd('-------消耗品订单ID----${state.order_id.value}');
        //消耗
        bool checkOrderResult = await GoodsAPI.apple_pay_verify_order(
          purchaseDetails.purchaseID.toString(),
          state.order_id.value,
        );
        return checkOrderResult;
      } else {
        logd('-------订单商品ID----${purchaseDetails.purchaseID.toString()}');

        //订阅
        if (state.order_id.value != '') {
          logd('-------订阅订单ID----${state.order_id.value}');

          bool checkOrderResult = await GoodsAPI.apple_pay_verify_order(
            purchaseDetails.purchaseID.toString(),
            state.order_id.value,
          );
          return checkOrderResult;
        } else {
          logd('-------恢复订单ID----${state.order_id.value}');
          bool checkOrderResult = await GoodsAPI.apple_pay_supplement_order(
            purchaseDetails.purchaseID.toString(),
          );
          return checkOrderResult;
        }
      }
    }
  }

  /// 交付商品
  /// 作用：在购买成功并验证通过后，向用户提供购买的商品
  Future<void> _deliverProduct(PurchaseDetails purchaseDetails) async {
    // 处理消耗品
    // if (purchaseDetails.productID == _kConsumableId) {
    //   await ConsumableStore.save(purchaseDetails.purchaseID!);
    //   final List<String> consumables = await ConsumableStore.load();
    //   _updateState(
    //     consumables: consumables,
    //     purchasePending: false,
    //   );
    // }
    // // 处理非消耗品和订阅
    // else {
    //   final List<PurchaseDetails> updatedPurchases = List.from(state.purchases);
    //   updatedPurchases.add(purchaseDetails);
    //   _updateState(
    //     purchases: updatedPurchases,
    //     purchasePending: false,
    //   );
    // }
  }

  /// 处理购买错误
  void _handleError(IAPError error) {
    // _updateState(purchasePending: false);
    // 可以在这里添加错误提示逻辑
  }

  /// 处理购买监听错误
  void _handlePurchaseError(Object error) {
    // 可以在这里添加错误日志记录或用户提示
    print('内购监听错误: $error');
  }

  /// 处理无效购买
  void _handleInvalidPurchase(PurchaseDetails purchaseDetails) {
    // 可以在这里添加无效购买的处理逻辑，如提示用户联系客服等
    print('无效的购买: ${purchaseDetails.productID}');
    // state.purchasePending.value = false;

    // _updateState(purchasePending: false);
  }
}

/// iOS支付队列代理
/// 作用：处理iOS平台特定的支付队列回调
class ExamplePaymentQueueDelegate implements SKPaymentQueueDelegateWrapper {
  /// 决定是否继续交易
  /// 可以在这里添加地区限制、用户权限检查等逻辑
  @override
  bool shouldContinueTransaction(
    SKPaymentTransactionWrapper transaction,
    SKStorefrontWrapper storefront,
  ) {
    return true; // 继续交易
  }

  /// 决定是否显示价格变更提示
  @override
  bool shouldShowPriceConsent() {
    return false; // 不显示价格变更提示（根据需求调整）
  }
}
